﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using Ants.SimpleDistributionProblem.DTO;

namespace Model
{
    /// <summary>
    /// Singleton providing methods to operate on data files.
    /// </summary>
    public class FileDataProvider
    {
        /// <summary>
        /// The instance.
        /// </summary>
        private static FileDataProvider instance;

        private const string path = "output.txt";

        /// <summary>
        /// Prevents a default instance of the <see cref="FileDataProvider" /> class from being created.
        /// </summary>
        private FileDataProvider()
        {
        }

        /// <summary>
        /// Gets the instance.
        /// </summary>
        /// <value>
        /// The instance.
        /// </value>
        public static FileDataProvider Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new FileDataProvider();
                }

                return instance;
            }
        }

        /// <summary>
        /// Opens the file.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <returns>The data.</returns>
        public Data OpenFile(string path)
        {
            string[] fileLines = File.ReadAllLines(path);
            List<Point> cities = new List<Point>();
            for (int i = 1; i < fileLines.Length; ++i)
            {
                string[] coords = fileLines[i].Split(' ');
                cities.Add(new Point(Convert.ToInt32(coords[0]), Convert.ToInt32(coords[1])));
            }

            return new Data()
            {
                K = Convert.ToInt32(fileLines[0]),
                Cities = cities
            };
        }

        public void SaveData(double cost, int routeNumber, List<Lap> laps) {
            List<string> fileLines = new List<string>();
            fileLines.Add(Convert.ToString(cost));
            fileLines.Add(Convert.ToString(routeNumber));
            foreach (Lap lap in laps) {
                string line = "";
                line += lap.CityIndices[0];
                for (int i = 1; i < lap.CityIndices.Count; ++i) {
                    line += " " + lap.CityIndices[i];
                }
                fileLines.Add(line);
            }
            File.WriteAllLines(path, fileLines); 
        }
    }
}